<?php

namespace app\api\service;

use app\admin\service\CommonService;
use app\models\DictionaryModel;
use app\models\StudentModel;
use app\models\UserModel;
use think\Cache;
use think\Log;

class MessageService
{
    private $appId = 'ww68a90ee5584d7cb7'; //我的企业ID
    private $appSecret = 'uzrl5p0AGWVt65Z6D8BcG_KqJZdNpRYah509YF4UYy4'; //自建应用里的Secret
    private $agentid = '1000010'; //AgentId 手动授权时scope值改为snsapi_privateinfo 后面必须有AgentId

    /**
     * 免费试用
     * User: Truman
     * Date: 2020/08/12.
     *
     * @param $data
     *
     * @throws \think\exception\DbException
     */
    public function freetrial($data)
    {
        //第一步：获取access_token
        $access_token = $this->getAccessToken();
		Log::record('第一步：获取access_token：'.json_encode($access_token),'freetrial');
        cache('access_token', $access_token, 7200);
        //第二步：获取所有部门
        $departmentList = $this->getDepartmentList($access_token);
		Log::record('第二步：获取所有部门：'.json_encode($departmentList),'freetrial');
        //第三步：获取公司下的所有员工
        $userList = $this->getUserList($access_token, $departmentList[0]['id']);
		Log::record('第三步：获取公司下的所有员工：'.json_encode($userList),'freetrial');

		$distribution_user_id = $distribution_name = '';
		if($data['parameter'] == ''){
			$distribution_name = '胡莞琴';
			$distribution_user_id = 44;
		}else{
			$distribution_name = $data['bound_people'];
			$distribution_user_id = (new UserModel())->get(['name'=>$data['bound_people']])['id'];
		}

        $customer_data = [];
        $customer_data['name'] = $data['name']; //书店名称
        $customer_data['student_name'] = $data['name']; //书店名称
        $customer_data['course_consultant'] = $distribution_name; //渠道专员
        $customer_data['channel'] = (new DictionaryModel())->get(['type' => 2, 'name' => '官网申请'])['id']; //来源渠道
        $customer_data['introduction'] = 0; //介绍人
        $customer_data['phone'] = $data['phone']; //电话
        $customer_data['guardian_phone'] = $data['phone']; //手机号码
        $customer_data['other_phone'] = $data['phone']; //更多联系人
        $customer_data['register_date'] = date('Y-m-d', strtotime($data['add_date']));
        $customer_data['follow_up_date'] = date('Y-m-d', strtotime($data['add_date']));
        $customer_data['follow_up_time'] = $data['add_date'];
        $customer_data['follow_up_timestamp'] = $data['add_time'];
        $customer_data['bound_phone'] = $data['bound_phone'];
        $customer_data['bound_people'] = $data['bound_people'];
        $customer_data['user_id'] = $distribution_user_id; //当前用户ID
        $customer_data['course_consultant_type'] = 1; //当前用户类型 课程顾问类型 1自己 2公海
        $customer_data['is_audition'] = 1; //类型 1：客户
        $customer_data['follow_up'] = 34; //未处理
        $customer_data['student_number'] = CommonService::generateStudentNumber();  //学号
        $customer_data_res = (new StudentModel())->save($customer_data);
		Log::record('录入数据结果返回：'.json_encode($customer_data_res),'freetrial');

        foreach ($userList as $value) {
            if ($value['name'] === $distribution_name) {
                $touser = $value['userid'];
                // $toparty = $value['department'][0];
                $toparty = '';
                $title = '免费体验申请通知';
                $date = date('Y-m-d');
                $description = '<div class=\"gray\">'.$date.'</div> <div class=\"normal\">免费体验申请人：'.$data['name'].'</div><div class=\"highlight\">请前往CRM系统及时联系客户</div>';
                $url = 'http://crm.haoshusugou.com/admin/account/login.html';
                $res = $this->push_card($touser, $toparty, $title, $description, $url);
				Log::record('免费体验申请通知结果：'.json_encode($res),'freetrial');
                break;
            }
        }
    }

    /**
     * 获取access_token
     * User: Truman
     * Date: 2020/08/11.
     *
     * @return bool
     */
    public function getAccessToken()
    {
        $code_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.$this->appId.'&corpsecret='.$this->appSecret;
        $access_token_str = curl_get($code_url);
        $access_token_list = json_decode($access_token_str, true);
        $access_token = $access_token_list['access_token']; //获取access_token
        if (0 === $access_token_list['errcode']) {
            return $access_token;
        }

        return false;
    }

    /**
     * 文本消息推送
     * touser、toparty、totag不能同时为空
     * touser 成员ID列表（消息接收者，多个接收者用‘|’分隔，最多支持1000个）。特殊情况：指定为@all，则向该企业应用的全部成员发送
     * toparty 部门ID列表，多个接收者用‘|’分隔，最多支持100个。当touser为@all时忽略本参数
     * totag 标签ID列表，多个接收者用‘|’分隔，最多支持100个。当touser为@all时忽略本参数
     * safe 表示是否是保密消息，0表示否，1表示是，默认0.
     *
     * @param $touser
     * @param $toparty
     * @param string $message //推送内容
     *
     * @return true or false
     */
    public function push_message($touser, $toparty, $message)
    {
        $access_token = cache('access_token');
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='.$access_token;
        $params = ['touser' => $touser, 'toparty' => $toparty, 'totag' => '', 'msgtype' => 'text', 'agentid' => $this->agentid, 'text' => ['content' => $message], 'safe' => 0];
        $data = json_decode(curl_post($url, $params), true);
        if (0 === $data['errcode']) {
            return true;
        }

        return false;
    }

    /**
     * //发送推送文本卡片消息展现.
     *
     * @param $touser
     * @param $toparty
     * @param $title
     * @param $description
     * @param $url
     *
     * @return bool|mixed
     */
    public function push_card($touser, $toparty, $title, $description, $url)
    {
        $access_token = cache('access_token');
        $push_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='.$access_token;
        $params = ['touser' => $touser, 'toparty' => $toparty, 'totag' => '', 'msgtype' => 'textcard', 'agentid' => $this->agentid, 'textcard' => ['title' => $title, 'description' => $description, 'url' => $url, 'btntxt' => '']];
        $data = json_decode(curl_post($push_url, $params), true);
        if (0 === $data['errcode']) {
            return $data;
        }

        return false;
    }

    /**
     * 获取部门列表
     * User: Truman
     * Date: 2020/08/11.
     *
     * @param $access_token
     *
     * @return bool
     */
    public function getDepartmentList($access_token)
    {
        $department_url = 'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token='.$access_token;
        $department_str = curl_get($department_url);
        $department_list = json_decode($department_str, true);
        if (0 === $department_list['errcode']) {
            return $department_list['department'];
        }

        return false;
    }

    /**
     * 获取公司下的所有员工
     * User: Truman
     * Date: 2020/08/11.
     *
     * @param $access_token
     * @param $id
     *
     * @return bool
     */
    public function getUserList($access_token, $id)
    {
        $user_url = 'https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token='.$access_token.'&department_id='.$id.'&fetch_child=1';
        $user_str = curl_get($user_url);
        $user_list = json_decode($user_str, true);
        if (0 === $user_list['errcode']) {
            return $user_list['userlist'];
        }

        return false;
    }

    //企业微信订单通知
    public function CompanyOrderNotify()
    {
        $url = 'http://wxtest.minicart.cn/ordernotify/qymessage/template?templateId=ORDER_NOTIFY';
        $data = '订单号： %s
                配送站：  %s
                车次：    %s
                座位：    %s
                商品：    %s
                订单金额：%s元
                下单时间：%s';
        $data = sprintf($data, 'A001', '长沙南', 'G1306', '4车厢12F', '牛肉面*1,', '10', '2018-01-01');

        $res = https_request($url, $data, 'POST', ['content-type:text/plain;charset=utf-8']);
        dump($data);
        dump($res);
    }
}
